<template>
  <view class="upload-video">
    <CardComHeader title="宣传视频" :des="getHeaderDes" />
    <template v-if="modelValue?.tempFilePath">
      <view class="edit-video">
        <image
          class="del-icon"
          @click="delVideo"
          src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/del-icon.png"
          mode="scaleToFill"
        />
        <VideoPlay v-model="getVideoInfo" />
      </view>
    </template>
    <TButton
      v-if="!modelValue?.tempFilePath"
      text="添加视频"
      icon="&#xe61f;"
      :customStyle="{
        backgroundColor: '#f5f5f5',
        border: '2rpx dashed #dddddd',
        color: '#808080',
      }"
      @click="chooseVideo"
    />
  </view>
</template>

<script setup lang="ts">
  import { computed, type PropType, watch, provide } from 'vue';
  import { fileDefaultSize, useUpload } from '@/hooks/core/useUpload';
  import VideoPlay from '@/components/VideoPlay/index.vue';
  import CardComHeader from '../cardComHeader/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';

  interface VideoInfo {
    /** 文件本地临时地址 */
    tempFilePath?: string;
    /** 视频缩略图临时文件路径 */
    thumbTempFilePath?: string;
  }

  const props = defineProps({
    modelValue: {
      type: Object as PropType<VideoInfo>,
      required: true,
    },
  });

  const emit = defineEmits(['update:modelValue']);

  const getHeaderDes = computed(() => `请上传${fileDefaultSize.video}M以内视频文件`);

  const { result, chooseFile, delResultItem } = useUpload({
    fileSize: fileDefaultSize.video,
    isUploadVideoCover: true,
    count: 1,
  });

  const getVideoInfo = computed(() => {
    const { tempFilePath, thumbTempFilePath } = props.modelValue;
    return {
      videoUrl: tempFilePath,
      coverUrl: thumbTempFilePath,
    };
  });

  watch(
    result,
    (val) => {
      const res = val[0];
      if (res && res.progress === 100) {
        emit('update:modelValue', {
          tempFilePath: res.filePath,
          thumbTempFilePath: res.thumbFilePath,
        });
      }
    },
    {
      deep: true,
    },
  );

  function chooseVideo() {
    chooseFile({ mediaType: 'video' });
  }

  function delVideo() {
    delResultItem(0);
    emit('update:modelValue', {
      tempFilePath: '',
      thumbTempFilePath: '',
    });
  }

  provide('isPlayVideo', () => {});
</script>

<style lang="scss" scoped>
  .upload-video {
    .edit-video {
      position: relative;
      .del-icon {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
        width: 32rpx;
        height: 32rpx;
        z-index: 2;
      }
    }
  }
</style>
